package com.googlecode.compliancechecker;
import java.io.IOException;
import java.io.InputStream;

import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;

/**
 * Utility class to detect the android api level a source file should be
 * compliant to.
 * 
 * @author Marc-Christian Schulze
 * 
 */
public class ComplianceLevelDetector implements ClassVisitor, AnnotationVisitor {

	private String	annotationName;
	private String	attributeName;
	private int		apiLevel;

	public ComplianceLevelDetector(String annotationName, String attributeName) {
		this.annotationName = annotationName;
		this.attributeName = attributeName;
	}

	public int getApiLevel(InputStream stream) throws IOException {
		ClassReader cr = new ClassReader(stream);
		cr.accept(this, 0);
		return apiLevel;
	}

	public AnnotationVisitor visitAnnotation(String arg0, boolean arg1) {
		Type type = Type.getType(arg0);
		if (annotationName.indexOf(".") == -1) {
			if (type.getClassName().endsWith("." + annotationName) || type.getClassName().equals(annotationName)) {
				return this;
			}
		} else {
			if (type.getClassName().equals(annotationName)) {
				return this;
			}
		}
		return null;
	}

	public void visit(String paramName, Object arg1) {
		if (paramName.equalsIgnoreCase(attributeName)) {
			apiLevel = Integer.parseInt(arg1.toString());
		}
	}

	public void visit(int arg0, int arg1, String arg2, String arg3, String arg4, String[] arg5) {
	}

	public void visitAttribute(Attribute arg0) {
	}

	public void visitEnd() {
	}

	public FieldVisitor visitField(int arg0, String arg1, String arg2, String arg3, Object arg4) {
		return null;
	}

	public void visitInnerClass(String arg0, String arg1, String arg2, int arg3) {
	}

	public MethodVisitor visitMethod(int arg0, String arg1, String arg2, String arg3, String[] arg4) {
		return null;
	}

	public void visitOuterClass(String arg0, String arg1, String arg2) {
	}

	public void visitSource(String arg0, String arg1) {
	}

	public AnnotationVisitor visitAnnotation(String arg0, String arg1) {
		return null;
	}

	public AnnotationVisitor visitArray(String arg0) {
		return null;
	}

	public void visitEnum(String arg0, String arg1, String arg2) {
	}
}
